package cn.book.bus.controller;



import cn.book.bus.domain.*;
import cn.book.bus.service.BoEuStudentEavResultService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.book.bus.service.SultsService;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * (Sults)表控制层
 *
 * @author makejava
 * @since 2024-01-17 15:00:53
 */
@RestController
@RequestMapping("sults")
public class SultsController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private SultsService sultsService;

    @Resource
    private BoEuStudentEavResultService boEuStudentEavResultService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param sults 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R selectAll(Page<Sults> page, Sults sults) {

        //10线程=
        //8线程=54s
        //7线程=59s
        //6线程=59s

        // 创建一个定长线程池，例如5个线程
        int threadCount = 8;
        ExecutorService executorService = Executors.newFixedThreadPool(threadCount);

        //所有数据
        List<Sults> sultsList = sultsService.list();
        // 数据分页大小，每个线程处理多少数据
        int batchSize = (sultsList.size() + threadCount - 1) / threadCount;
        // 将大列表拆分成多个小列表，然后提交到线程池处理
        for (int i = 0; i < sultsList.size(); i += batchSize) {
            final int fromIndex = i;
            final int toIndex = Math.min(fromIndex + batchSize, sultsList.size());
            Runnable worker = () -> processBatchbanji(sultsList.subList(fromIndex, toIndex));
            executorService.submit(worker);
        }
        // 关闭线程池，等待所有任务完成
        executorService.shutdown();
        try {
            // 阻塞直到所有任务都已完成
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("Interrupted while waiting for tasks to terminate.");
        }




//        List<Sults> sultsList = sultsService.list();
////        final val subList = sultsList.subList(0, 8);
//
//        int count =0;
//
//        for (Sults sults1 : sultsList) {
//            count++;
//            System.out.println("count===="+count);
////            final val wrapper = new LambdaQueryWrapper<BoEuStudentEavResult>();
////            wrapper.eq(BoEuStudentEavResult::getId,sults1.getId());
////            final val one = boEuStudentEavResultService.getOne(wrapper);
//            BoEuStudentEavResult one = boEuStudentEavResultService.getById(sults1.getId());
//            if (one.getTaskStatus().equals(sults1.getTaskStatus())){
//                continue;
//            }else {
//                System.out.println(one);
//                System.out.println(sults1);
//                sults1.setTaskStatus("已评教");
//                sultsService.updateById(sults1);
////                break;
//            }
//
//        }
//
//        System.out.println(sultsList.size());
        return success("ok");
//        return success(this.sultsService.page(page, new QueryWrapper<>(sults)));
    }

    private  void processBatchbanji(List<Sults> sultss) {
        int count = 0;
        int sum = 0;
        for (Sults sults : sultss) {
            count++;

            BoEuStudentEavResult one = boEuStudentEavResultService.getById(sults.getId());
            if (one.getTaskStatus().equals(sults.getTaskStatus())){
                continue;
            }else {
                sum++;
                System.out.println(sum);
                System.out.println("20240115results====="+sults);
                System.out.println("bo_eu_student_eav_result====="+one);

                if (one.getTaskStatus().equals("已评教")){
                    sults.setTaskStatus("已评教");
                }
                if (one.getTaskStatus().equals("未评教")){
                    sults.setTaskStatus("未评教");
                }

                sultsService.updateById(sults);
//                break;
            }

        }
        System.out.println("count======="+count);
        System.out.println("sum======="+sum);

    }




    @GetMapping("list")
    public void simpleRead1() {
        final ArrayList<chepingxiangqing> cepings = new ArrayList<>();
        QueryWrapper<Sults> wrapper = new QueryWrapper<>();
        wrapper.eq("TASK_STATUS","未评教");
        wrapper.groupBy("STUDENT_ID","STUDENT_NAME","CLASS_ID","CLASS_NAME","XB","XQ","FDY","FDYHM");
        wrapper.select("STUDENT_ID,STUDENT_NAME,CLASS_ID,CLASS_NAME,XB,XQ,FDY,FDYHM", "count(STUDENT_ID) count");
         List<Map<String, Object>> selectMaps = sultsService.getBaseMapper().selectMaps(wrapper);
        for (Map<String, Object> map : selectMaps) {
            System.out.println(map.get("STUDENT_NAME") + " " + map.get("count"));
             chepingxiangqing chepingxiangqing = new chepingxiangqing();
             chepingxiangqing.setSTUDENT_ID(map.get("STUDENT_ID").toString());
             chepingxiangqing.setSTUDENT_NAME(map.get("STUDENT_NAME").toString());
             chepingxiangqing.setCLASS_ID(map.get("CLASS_ID").toString());
             chepingxiangqing.setCLASS_NAME(map.get("CLASS_NAME").toString());
             chepingxiangqing.setXB(map.get("XB").toString());
             chepingxiangqing.setXQ(map.get("XQ").toString());
             chepingxiangqing.setStatus("未评教完成");
             chepingxiangqing.setFDY(map.get("FDY").toString());
             chepingxiangqing.setFDYHM(map.get("FDYHM").toString());
             chepingxiangqing.setCOUNT(map.get("count").toString());
            cepings.add(chepingxiangqing);
        }


        final String property = System.getProperty("user.dir");

        System.out.println(property);


        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
        String formattedDateTime = now.format(formatter);
        System.out.println("当前时间：" + formattedDateTime);

        String fileName2 = property+"\\src\\main\\java\\cn\\book\\bus\\controller\\" + "评测详情" + formattedDateTime + ".xlsx";


        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName2, chepingxiangqing.class)
                .sheet("模板")
                .doWrite(() -> {
                    // 分页查询数据
                    return cepings;
                });
    }

    @GetMapping("list2")
    public void simpleRead2() {
        QueryWrapper<Sults> wrapper = new QueryWrapper<>();
//        wrapper.eq("TASK_STATUS","未评教");
//        wrapper.select("DISTINCT STUDENT_ID,STUDENT_NAME,TASK_STATUS,FDY,FDYHM");

//        wrapper.eq("TASK_STATUS","未评教");
        wrapper.select("DISTINCT STUDENT_ID,STUDENT_NAME,FDY,FDYHM,XB,XQ");
        List<Map<String, Object>> totalmapList = sultsService.getBaseMapper().selectMaps(wrapper);

        QueryWrapper<Sults> wrapper1 = new QueryWrapper<>();
               wrapper1.eq("TASK_STATUS","未评教");
        wrapper1.select("DISTINCT STUDENT_ID,STUDENT_NAME,TASK_STATUS,FDY,FDYHM");

        wrapper1.eq("TASK_STATUS","未评教");
        List<Map<String, Object>> notmapList = sultsService.getBaseMapper().selectMaps(wrapper1);

        HashSet<String> set = new HashSet<>();

         for (Map<String, Object> map : totalmapList) {
            set.add(map.get("FDY").toString());
        }

        ArrayList<Fdaoyuan> fdaoyuans = new ArrayList<>();
        for (String string : set) {
            Fdaoyuan fdaoyuan = new Fdaoyuan();
            fdaoyuan.setFDY(string);
            for (Map<String, Object> map : totalmapList) {
                if (map.get("FDY").toString().equals(string)) {
                     fdaoyuan.setFDYHM(map.get("FDYHM").toString());
                     fdaoyuan.setXB(map.get("XB").toString());
                     fdaoyuan.setXQ(map.get("XQ").toString());
                }
        }

            fdaoyuans.add(fdaoyuan);

//         ArrayList<Fdaoyuan> fdaoyuans = new ArrayList<>();
//        int size = set.size();
//        System.out.println(size);
//        for (String string : set) {
//             Fdaoyuan fdaoyuan = new Fdaoyuan();
//             fdaoyuan.setFDY(string);
//             int count = 0;
//             for (Map<String, Object> map : mapList) {
//                 if (map.get("FDY").toString().equals(string)) {
//                     count++;
//                     fdaoyuan.setFDYHM(map.get("FDYHM").toString());
//                 }
//             }
//             fdaoyuan.setCOUNT(String.valueOf(count));
//            fdaoyuans.add(fdaoyuan);

        }

        for (Fdaoyuan fdaoyuan : fdaoyuans) {
            int count = 0;
            int notcount = 0;
            for (Map<String, Object> map : totalmapList) {
                if (map.get("FDY").toString().equals(fdaoyuan.getFDY())) {
                    count++;
                }
            }
            for (Map<String, Object> map : notmapList) {
                if (map.get("FDY").toString().equals(fdaoyuan.getFDY())) {
                    notcount++;
                }
            }
            fdaoyuan.setCOUNT(String.valueOf(count));
            fdaoyuan.setNOTCOUNT(String.valueOf(notcount));
            int finishcount = count - notcount;
            fdaoyuan.setFINISHCOUNT(String.valueOf(count - notcount));
             BigDecimal countDecimal = new BigDecimal(count);
             BigDecimal finishcountDecimal = new BigDecimal(finishcount);
             BigDecimal decimal = finishcountDecimal.divide(countDecimal, 2,BigDecimal.ROUND_UP);
            fdaoyuan.setCOMPLETIONRATE(decimal.toString());
        }

        final String property = System.getProperty("user.dir");

        System.out.println(property);


        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
        String formattedDateTime = now.format(formatter);
        System.out.println("当前时间：" + formattedDateTime);

        String fileName2 = property+"\\src\\main\\java\\cn\\book\\bus\\controller\\" + "辅导员评测详情" + formattedDateTime + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName2, Fdaoyuan.class)
                .sheet("模板")
                .doWrite(() -> {
                    // 分页查询数据
                    return fdaoyuans;
                });
    }

    @GetMapping("list3")
    public void simpleRead3() {
        QueryWrapper<Sults> wrapper = new QueryWrapper<>();


        wrapper.select("DISTINCT XB");
        List<Map<String, Object>> xbList = sultsService.getBaseMapper().selectMaps(wrapper);

        QueryWrapper<Sults> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("TASK_STATUS","未评教");
        wrapper1.select("DISTINCT STUDENT_ID,STUDENT_NAME,TASK_STATUS,XB");
        List<Map<String, Object>> notmapList = sultsService.getBaseMapper().selectMaps(wrapper1);

        QueryWrapper<Sults> wrapper2 = new QueryWrapper<>();
        wrapper2.select("DISTINCT STUDENT_ID,STUDENT_NAME,XB");
        List<Map<String, Object>> tatalmapList = sultsService.getBaseMapper().selectMaps(wrapper2);

         ArrayList<Xbxq> xbxqArrayList = new ArrayList<>();
        for (Map<String, Object> map : xbList) {
            int count = 0;
            int notcount = 0;
             Xbxq xbxq = new Xbxq();

             String xb = (String) map.get("XB");

            for (Map<String, Object> objectMap : notmapList) {
                String s=(String) objectMap.get("XB");
                if (xb.equals(s)){
                    notcount++;
                }
            }

            for (Map<String, Object> Map : tatalmapList) {
                String y = (String) Map.get("XB");
                if (xb.equals(y)){
                    count++;
                }
            }

            xbxq.setXB(xb);
            xbxq.setCOUNT(String.valueOf(count));
            xbxq.setNOTCOUNT(String.valueOf(notcount));

            xbxqArrayList.add(xbxq);

        }


         String property = System.getProperty("user.dir");

        System.out.println(property);

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
        String formattedDateTime = now.format(formatter);
        System.out.println("当前时间：" + formattedDateTime);


        String fileName2 = property+"\\src\\main\\java\\cn\\book\\bus\\controller\\" + "系部统计详情" + formattedDateTime + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName2, Xbxq.class)
                .sheet("模板")
                .doWrite(() -> {
                    // 分页查询数据
                    return xbxqArrayList;
                });
    }

//    private  void processBatch(List<BoEuDbTeacher> batch,ArrayList<banji> arrayList) {
//        for (BoEuDbTeacher boEuDbTeacher : batch) {
//            final banji banji = new banji();
//            banji.setId(boEuDbTeacher.getTeacherCode());
//            banji.setName(boEuDbTeacher.getTeacherName());
//
//
//
//            final String teacherCode = boEuDbTeacher.getTeacherCode();
//            final LambdaQueryWrapper<BoEuStudentEavResult> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(BoEuStudentEavResult::getTeacherCode, teacherCode);
//            final int count = boEuStudentEavResultService.count(wrapper);
//            banji.setTatol(String.valueOf(count));
//
//            final LambdaQueryWrapper<BoEuStudentEavResult> wrapper1 = new LambdaQueryWrapper<>();
//            wrapper1.eq(BoEuStudentEavResult::getTeacherCode, teacherCode).eq(BoEuStudentEavResult::getTaskStatus,"未评教");
//            final int count1 = boEuStudentEavResultService.count(wrapper1);
//            banji.setWeiping(String.valueOf(count1));
//
//
//            final LambdaQueryWrapper<BoEuStudentEavResult> wrapper2 = new LambdaQueryWrapper<>();
//            wrapper2.eq(BoEuStudentEavResult::getTeacherCode, teacherCode).eq(BoEuStudentEavResult::getTaskStatus,"已评教");
//            final int count2 = boEuStudentEavResultService.count(wrapper2);
//            banji.setYiping(String.valueOf(count2));
//
//            arrayList.add(banji);
//        }

    }




